import { createSlice, createAsyncThunk } from '@reduxjs/toolkit'
import { getAttendanceList, getAttendanceDetail, createAttendance, updateAttendance, deleteAttendance, getMyAttendance } from '../api/attendance'

// 异步获取考勤列表
export const fetchAttendances = createAsyncThunk(
  'attendance/fetchAttendances',
  async (params, { rejectWithValue }) => {
    try {
      const response = await getAttendanceList(params)
      return response
    } catch (error) {
      return rejectWithValue(error.response?.data || { message: '获取考勤列表失败' })
    }
  }
)

// 异步获取个人考勤记录
export const fetchMyAttendance = createAsyncThunk(
  'attendance/fetchMyAttendance',
  async (params, { rejectWithValue }) => {
    try {
      const response = await getMyAttendance(params)
      return response
    } catch (error) {
      return rejectWithValue(error.response?.data || { message: '获取个人考勤记录失败' })
    }
  }
)

// 异步获取考勤详情
export const fetchAttendanceDetail = createAsyncThunk(
  'attendance/fetchAttendanceDetail',
  async (id, { rejectWithValue }) => {
    try {
      const response = await getAttendanceDetail(id)
      return response.data
    } catch (error) {
      return rejectWithValue(error.response?.data || { message: '获取考勤详情失败' })
    }
  }
)

// 异步创建考勤记录
export const addAttendance = createAsyncThunk(
  'attendance/addAttendance',
  async (attendanceData, { rejectWithValue }) => {
    try {
      const response = await createAttendance(attendanceData)
      return response.data
    } catch (error) {
      return rejectWithValue(error.response?.data || { message: '添加考勤记录失败' })
    }
  }
)

// 异步更新考勤记录
export const editAttendance = createAsyncThunk(
  'attendance/editAttendance',
  async ({ id, data }, { rejectWithValue }) => {
    try {
      const response = await updateAttendance(id, data)
      return response.data
    } catch (error) {
      return rejectWithValue(error.response?.data || { message: '更新考勤记录失败' })
    }
  }
)

// 异步删除考勤记录
export const removeAttendance = createAsyncThunk(
  'attendance/removeAttendance',
  async (id, { rejectWithValue }) => {
    try {
      await deleteAttendance(id)
      return id
    } catch (error) {
      return rejectWithValue(error.response?.data || { message: '删除考勤记录失败' })
    }
  }
)

const initialState = {
  attendances: [],
  myAttendances: [],
  currentAttendance: null,
  pagination: {
    current: 1,
    pageSize: 10,
    total: 0
  },
  myPagination: {
    current: 1,
    pageSize: 10,
    total: 0
  },
  loading: false,
  error: null,
  statistics: {
    present: 0,
    absent: 0,
    late: 0,
    leave: 0
  }
}

const attendanceSlice = createSlice({
  name: 'attendance',
  initialState,
  reducers: {
    clearError: (state) => {
      state.error = null
    },
    setCurrentPage: (state, action) => {
      state.pagination.current = action.payload
    },
    setPageSize: (state, action) => {
      state.pagination.pageSize = action.payload
    },
    setMyCurrentPage: (state, action) => {
      state.myPagination.current = action.payload
    },
    setMyPageSize: (state, action) => {
      state.myPagination.pageSize = action.payload
    },
    clearCurrentAttendance: (state) => {
      state.currentAttendance = null
    }
  },
  extraReducers: (builder) => {
    builder
      // 获取考勤列表
      .addCase(fetchAttendances.pending, (state) => {
        state.loading = true
        state.error = null
      })
      .addCase(fetchAttendances.fulfilled, (state, action) => {
        state.loading = false
        state.attendances = action.payload.data || []
        state.pagination.total = action.payload.total || 0
        // 更新统计数据
        if (action.payload.statistics) {
          state.statistics = action.payload.statistics
        }
      })
      .addCase(fetchAttendances.rejected, (state, action) => {
        state.loading = false
        state.error = action.payload?.message || '获取考勤列表失败'
      })
      // 获取个人考勤记录
      .addCase(fetchMyAttendance.pending, (state) => {
        state.loading = true
        state.error = null
      })
      .addCase(fetchMyAttendance.fulfilled, (state, action) => {
        state.loading = false
        state.myAttendances = action.payload.data || []
        state.myPagination.total = action.payload.total || 0
        // 更新个人统计数据
        if (action.payload.statistics) {
          state.statistics = action.payload.statistics
        }
      })
      .addCase(fetchMyAttendance.rejected, (state, action) => {
        state.loading = false
        state.error = action.payload?.message || '获取个人考勤记录失败'
      })
      // 获取考勤详情
      .addCase(fetchAttendanceDetail.pending, (state) => {
        state.loading = true
        state.error = null
      })
      .addCase(fetchAttendanceDetail.fulfilled, (state, action) => {
        state.loading = false
        state.currentAttendance = action.payload
      })
      .addCase(fetchAttendanceDetail.rejected, (state, action) => {
        state.loading = false
        state.error = action.payload?.message || '获取考勤详情失败'
      })
      // 添加考勤记录
      .addCase(addAttendance.pending, (state) => {
        state.loading = true
        state.error = null
      })
      .addCase(addAttendance.fulfilled, (state) => {
        state.loading = false
      })
      .addCase(addAttendance.rejected, (state, action) => {
        state.loading = false
        state.error = action.payload?.message || '添加考勤记录失败'
      })
      // 更新考勤记录
      .addCase(editAttendance.pending, (state) => {
        state.loading = true
        state.error = null
      })
      .addCase(editAttendance.fulfilled, (state) => {
        state.loading = false
      })
      .addCase(editAttendance.rejected, (state, action) => {
        state.loading = false
        state.error = action.payload?.message || '更新考勤记录失败'
      })
      // 删除考勤记录
      .addCase(removeAttendance.pending, (state) => {
        state.loading = true
        state.error = null
      })
      .addCase(removeAttendance.fulfilled, (state, action) => {
        state.loading = false
        state.attendances = state.attendances.filter(attendance => attendance.id !== action.payload)
      })
      .addCase(removeAttendance.rejected, (state, action) => {
        state.loading = false
        state.error = action.payload?.message || '删除考勤记录失败'
      })
  }
})

export const { 
  clearError, 
  setCurrentPage, 
  setPageSize, 
  setMyCurrentPage, 
  setMyPageSize, 
  clearCurrentAttendance 
} = attendanceSlice.actions

export default attendanceSlice.reducer